package com.hmall.trade.listener;

import com.hmall.api.clients.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.constants.MQConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.impl.OrderServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class OrderDelayListener {
    private final OrderServiceImpl orderService;
    private final PayClient payClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.DELAY_ORDER_QUEUE_NAME,durable = "true"),
            exchange = @Exchange(name = MQConstants.DELAY_EXCHANGE_NAME,delayed = "true"),//开启延迟队列
            key = MQConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelayMessage(Long orderId){
        //1.查询订单
        Order order = orderService.getById(orderId);
        //2.检测订单状态是否为已支付
        if (order!=null && order.getStatus()!=1) {
            //订单存在且是除了未支付的任何状态
            return;
        }
        //3.未支付，去查询支付表，判断流水状态
        PayOrderDTO payOrder = payClient.queryPayOrderByBizOrderNo(orderId);
        if (payOrder!=null && payOrder.getStatus()==3) {
            //4.1已支付，标记订单状态为已支付
            orderService.markOrderPaySuccess(orderId);
        }else {
            //4.1未支付，取消订单(将订单标记为已经关闭，恢复库存)
            orderService.cancelOrder(orderId);
        }
    }
}
